﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

using mbine.msgc.model;
using mbine.msgc.tool;

namespace mbine.msgc.controls
{
    /// <summary>
    /// Interaction logic for UCLogin.xaml
    /// </summary>
    public partial class UCLogin : UserControl
    {
        public string UId { get; set; }
        public string UPwd { get; set; }
        public event EventHandler EventLoginOk;
        public event EventHandler EventLoginFail;

        public UCLogin()
        {
            InitializeComponent();
        }

        private void btnLogin_Click(object sender, RoutedEventArgs e)
        {
            if (tbId.Text != "" && tbPassword.Text != "")
            {
                UId = tbId.Text;
                UPwd = tbPassword.Text;

                Login();
            }
        }

        public void Login()
        {
            CCUser.Instance.Email = UId;
            CCUser.Instance.Password = UPwd;
            CCUser.Instance.PrivateKey = CCUser.Instance.Email + DateTime.Now.Ticks.ToString();

            CAuthenServer authServer = new CAuthenServer(CInfo.Instance.Info["loginserver"], CInfo.Instance.Info["loginserverpath"]);
            authServer.EventError += new EventHandler(authServer_EventError);
            authServer.DataReceived += new EventHandler(authServer_DataReceived);
            authServer.Request(CCUser.Instance.Email, CCUser.Instance.Password.Md5(), CCUser.Instance.PrivateKey);
        }

        void authServer_DataReceived(object sender, EventArgs e)
        {
            string s = ((CAuthenServer)sender).GetData;

            CServerMessage ServerMessage = new CServerMessage();
            if (ServerMessage.LoginCheck(s))
            {
                CRoster.Instance.Set(ServerMessage.Data);           //성공시에 Roster 생성
                CCUser.Instance.AuthKey = ServerMessage.AuthKey;    //인증키 Assign
                ServerConnect();                                    //Msg Server에 연결 시도

                if (EventLoginOk != null)
                    EventLoginOk(this, null);
            }
            else
            {
                if (EventLoginFail != null)
                    EventLoginFail(this, null);

                MessageBox.Show(ServerMessage.Message);
            }
        }

        void authServer_EventError(object sender, EventArgs e)
        {
        }

        void ServerConnect()
        {
            CConnection.Instance.Server = new CMsgServer(CInfo.Instance.Info["servername"]
                , int.Parse(CInfo.Instance.Info["serverport"]));
            CConnection.Instance.Connect();
        }
    }
}
